//
//  InstallationDetailVCHelper.swift
//  ezyform
//
//  Created by Moennig Q on 25/3/2022.
//  Copyright © 2022 Client.Solution Pty Ltd. All rights reserved.
//

import UIKit
import SwiftyJSON
import MBProgressHUD
import MessageUI
import HandyJSON
enum RequiredDataForSign: String{
    case installDate = "Date of completion"
    case installerFullName = "Installer name"
    case accreditationNumber = "Accreditation number"
    case typeOfConnection = "Type of connection"
    case installationAddress = "Installation Address"
    case designerName = "Designer name"
    case AccreditationType = "Accreditation type"
    case deemedYears = "Deemed Years"
    case stscQuantity = "REC Quantity"
    case agent = "Agent"
    case company = "Company"
}
open class InstallationDetailVCHelper {
    static let shared = InstallationDetailVCHelper()
    //返回值为”“表示必填项全部都有值，不会空表示有确实的信息
    func checkReqiredInfoWhenInstallerAndDesignerSign()->String{
        var requirdMsg: String = ""
        //installer
        let signatures = JobDetailModelHelper.shared.jobDetailModel.signatures
        let systemDetail = JobDetailModelHelper.shared.jobDetailModel.system_detail
        let installationInfo = JobDetailModelHelper.shared.jobDetailModel.install_address
        //installer
        let installationDate = systemDetail.installation_date
        let installerName = signatures.installer_full_name
        let accreditedNumber = signatures.installer_accredited_number
        let typeOfConnection = systemDetail.type_of_connection
        let installationAddress = installationInfo.installation_address
        //designer
        let designerName = signatures.designer_full_name
//        let designerAccreditedNumber = signatures.designer_accredited_number ?? ""//是同一个人，只检查installer的即可
        let accreditedType = signatures.designer_accreditation_type
        
        //installer
        requirdMsg = (installationDate == "" ? RequiredDataForSign.installDate.rawValue + ", " : "")//首先要先检查Date of completion
        requirdMsg += (installerName == "" ? RequiredDataForSign.installerFullName.rawValue + ", " : "")
        requirdMsg += (accreditedNumber == "" ? RequiredDataForSign.accreditationNumber.rawValue + ", " : "")
        requirdMsg += (typeOfConnection == "" ? RequiredDataForSign.typeOfConnection.rawValue + ", " : "")
        requirdMsg += (installationAddress == "" ? RequiredDataForSign.installationAddress.rawValue + ", " : "")
        //designer
        requirdMsg += (designerName == "" ? RequiredDataForSign.designerName.rawValue + ", " : "")
//        requirdMsg += (designerAccreditedNumber == "" ? RequiredDataForSign.accreditationNumber.rawValue + ", " : "")
        requirdMsg += (accreditedType == "" ? RequiredDataForSign.AccreditationType.rawValue + ", " : "")
        
        if requirdMsg.count > 2{
            requirdMsg.remove(at: requirdMsg.index(requirdMsg.endIndex, offsetBy: -2))
            requirdMsg = "Missing " + requirdMsg
        }
        return requirdMsg
    }
    //返回值为”“表示必填项全部都有值，不会空表示有确实的信息
    func checkReqiredInfoWhenInstallerSign()->String{
        var requirdMsg: String = ""
        
        let signatures = JobDetailModelHelper.shared.jobDetailModel.signatures
        let systemDetail = JobDetailModelHelper.shared.jobDetailModel.system_detail
        let installationInfo = JobDetailModelHelper.shared.jobDetailModel.install_address
        
        let installationDate = systemDetail.installation_date
        let installerName = signatures.installer_full_name
        let accreditedNumber = signatures.installer_accredited_number
        let typeOfConnection = systemDetail.type_of_connection
        let installationAddress = installationInfo.installation_address
        
        requirdMsg = (installationDate == "" ? RequiredDataForSign.installDate.rawValue + ", " : "")//首先要先检查Date of completion
        requirdMsg += (installerName == "" ? RequiredDataForSign.installerFullName.rawValue + ", " : "")
        requirdMsg += (accreditedNumber == "" ? RequiredDataForSign.accreditationNumber.rawValue + ", " : "")
        requirdMsg += (typeOfConnection == "" ? RequiredDataForSign.typeOfConnection.rawValue + ", " : "")
        requirdMsg += (installationAddress == "" ? RequiredDataForSign.installationAddress.rawValue + ", " : "")
        //
        if requirdMsg.count > 2{
            requirdMsg.remove(at: requirdMsg.index(requirdMsg.endIndex, offsetBy: -2))
            requirdMsg = "Missing " + requirdMsg
        }
        return requirdMsg
    }
    func checkReqiredInfoWhenDesignerSign()->String{
        var requirdMsg: String = ""
        
        let signatures = JobDetailModelHelper.shared.jobDetailModel.signatures
        let systemDetail = JobDetailModelHelper.shared.jobDetailModel.system_detail
        let installationInfo = JobDetailModelHelper.shared.jobDetailModel.install_address
        
        let installationDate = systemDetail.installation_date
        let designerName = signatures.designer_full_name
        let accreditedNumber = signatures.designer_accredited_number
        let accreditedType = signatures.designer_accreditation_type
        let installationAddress = installationInfo.installation_address
        
        requirdMsg = (installationDate == "" ? RequiredDataForSign.installDate.rawValue + ", " : "")//首先要先检查Date of completion
        requirdMsg += (designerName == "" ? RequiredDataForSign.designerName.rawValue + ", " : "")
        requirdMsg += (accreditedNumber == "" ? RequiredDataForSign.accreditationNumber.rawValue + ", " : "")
        requirdMsg += (accreditedType == "" ? RequiredDataForSign.AccreditationType.rawValue + ", " : "")
        requirdMsg += (installationAddress == "" ? RequiredDataForSign.installationAddress.rawValue + ", " : "")
        //
        if requirdMsg.count > 2{
            requirdMsg.remove(at: requirdMsg.index(requirdMsg.endIndex, offsetBy: -2))
            requirdMsg = "Missing " + requirdMsg
        }
        return requirdMsg
    }
    func checkReqiredInfoWhenOwnerSign()->String{
        //需要区分OSW，非OSW
        let systemDetail = JobDetailModelHelper.shared.jobDetailModel.system_detail
        var requirdMsg: String = ""
        let installedDate = systemDetail.installation_date
        let deemYears = systemDetail.deemed_years
        let STCs = systemDetail.rec_quantity
        //common
        requirdMsg = (installedDate == "" ? RequiredDataForSign.installDate.rawValue + ", " : "")//首先要先检查Date of completion
        requirdMsg += (deemYears == "" ? RequiredDataForSign.deemedYears.rawValue + ", " : "")
        requirdMsg += (STCs == "" ? RequiredDataForSign.stscQuantity.rawValue + ", " : "")
        
        if JobDetailModelHelper.shared.jobDetailModel.is_osw_agent == false {//agent is osw
            let agentName = JobDetailModelHelper.shared.jobDetailModel.agent_name
            let company = JobDetailModelHelper.shared.jobDetailModel.company
            
            requirdMsg += (agentName == "" ? RequiredDataForSign.agent.rawValue + ", " : "")
            requirdMsg += (company == "" ? RequiredDataForSign.company.rawValue + ", " : "")
        }
        //
        if requirdMsg.count > 0{
            requirdMsg.remove(at: requirdMsg.index(requirdMsg.endIndex, offsetBy: -2))
            requirdMsg = "Missing " + requirdMsg
        }
        return requirdMsg
    }
    func checkReqiredInfoWhenWitnessSign()->String{
        var requirdMsg: String = ""
        let systemDetail = JobDetailModelHelper.shared.jobDetailModel.system_detail
        let installationDate = systemDetail.installation_date
        
        requirdMsg = (installationDate == "" ? RequiredDataForSign.installDate.rawValue : "")//首先要先检查Date of completion
        //
        if requirdMsg.count > 0{
            requirdMsg = "Missing " + requirdMsg
        }
        return requirdMsg
    }
    //获取designer签协议时，当时的数据的json字符串，传给后台
    func getAllRequiredJsonForSign(signTypes: [SignatureType])-> String{
        let dic = NSMutableDictionary()
        //Installer: 获取签协议时，当时的数据的json字符串，传给后台
        if signTypes.contains(.Installer){
            dic.setValue((JobDetailModelHelper.shared.jobDetailModel.system_detail.installation_date), forKey: "installation_date")
            dic.setValue((JobDetailModelHelper.shared.jobDetailModel.signatures.installer_full_name), forKey: "installer_full_name")
            dic.setValue((JobDetailModelHelper.shared.jobDetailModel.signatures.installer_accredited_number), forKey: "installer_accredited_number")
            dic.setValue((JobDetailModelHelper.shared.jobDetailModel.system_detail.type_of_connection), forKey: "type_of_connection")
            dic.setValue((JobDetailModelHelper.shared.jobDetailModel.install_address.installation_address), forKey: "installation_address")
        }
        //Designer: 获取签协议时，当时的数据的json字符串，传给后台
        if signTypes.contains(.Designer){
            dic.setValue((JobDetailModelHelper.shared.jobDetailModel.system_detail.installation_date), forKey: "installation_date")
            dic.setValue((JobDetailModelHelper.shared.jobDetailModel.signatures.designer_full_name ), forKey: "designer_full_name")
            dic.setValue((JobDetailModelHelper.shared.jobDetailModel.signatures.designer_accredited_number ), forKey: "designer_accredited_number")
            dic.setValue((JobDetailModelHelper.shared.jobDetailModel.signatures.designer_accreditation_type ), forKey: "designer_accreditation_type")
            dic.setValue((JobDetailModelHelper.shared.jobDetailModel.install_address.installation_address), forKey: "installation_address")
        }
        //Owner: 获取签协议时，当时的数据的json字符串，传给后台
        if signTypes.contains(.Owner){
            dic.setValue(JobDetailModelHelper.shared.jobDetailModel.agent_name, forKey: "agent_name")
            dic.setValue(JobDetailModelHelper.shared.jobDetailModel.company, forKey: "company")
            dic.setValue((JobDetailModelHelper.shared.jobDetailModel.system_detail.installation_date ), forKey: "installation_date")
            dic.setValue((JobDetailModelHelper.shared.jobDetailModel.signatures.owner_type_name ), forKey: "owner_full_name")
            dic.setValue((JobDetailModelHelper.shared.jobDetailModel.system_detail.deemed_years), forKey: "deemed_years")
            dic.setValue((JobDetailModelHelper.shared.jobDetailModel.system_detail.rec_quantity ), forKey: "rec_quantity")
        }
        if let data = try? JSONSerialization.data(withJSONObject: dic, options: JSONSerialization.WritingOptions.init(rawValue: 0)){
            if let jsonStr = NSString(data: data, encoding: String.Encoding.utf8.rawValue){
                return jsonStr as String
            }
        }
        return ""
    }
    //MARK: -检查所有后台配置的checklist必填项是否完成,
    func checkIfChecklistAllDoneForPanelInstalled()->(String, String,[Int32]){
        var notDoneChecklistIDs: [Int32] = []//没有完成的image类型的checklist id
        //******1.Checklist
        var alertMsg: String = ""
        var minImagesCntMsg: String = ""//用于image类型的配置了最小image数量的校验
        let allRequiredCheckList: [PVDChecklistModel] = JobDetailModelHelper.shared.jobDetailModel.pvd_checklists.filter({$0.originalChecklistFlag == true && $0.is_required == "true" && ($0.type == ChecklistType.Image.rawValue || $0.type == ChecklistType.Text.rawValue || $0.type == ChecklistType.Bool.rawValue)})
        for checklistModel in allRequiredCheckList {
            let title = checklistModel.title
            switch checklistModel.type {
                case ChecklistType.Bool.rawValue:
                    if checklistModel.answer == "" || checklistModel.answer == "false" {
                        alertMsg += "* " + title + " must be checked.\n"
                        notDoneChecklistIDs.append(checklistModel.id)
                    }
                case ChecklistType.Image.rawValue:
                    //ESC单独处理,如果COC附件有数据，则表示此checklist已完成（也不用检查是否满足最小数量）
                    let cocCnt = JobDetailModelHelper.shared.jobDetailModel.coc_documents.count
                    let electricalFlag = checklistModel.actions.electrical
                    if electricalFlag && cocCnt > 0{//表示ESC完成
                        
                    }else{//其他情况
                        let realImageCount = checklistModel.images.count
                        if realImageCount == 0 {
                            alertMsg += "* " + title + " must be checked.\n"
                            notDoneChecklistIDs.append(checklistModel.id)
                        }else {
                            let minImagesCnt = checklistModel.minimum_quantity
                            if realImageCount < minImagesCnt{//如果checklist的image 数量小于配置的最小图片数量，也要提示没有完成
                                minImagesCntMsg += " - " + title + " (\(realImageCount)/\(minImagesCnt)).\n"
                                notDoneChecklistIDs.append(checklistModel.id)
                            }
                        }
                    }
                case ChecklistType.Text.rawValue:
                    if checklistModel.answer == "" {
                        alertMsg += "* " + title + " must be checked.\n"
                        notDoneChecklistIDs.append(checklistModel.id)
                    }
                default:
                    break
            }
        }
        return (alertMsg, minImagesCntMsg,notDoneChecklistIDs)
    }
    //MARK: -检查所有后台配置的checklist必填项是否完成，以及NOC
    func checkIfChecklistAllDoneForFinishJob()->(String, String){
        //******1.Checklist
        var alertMsg: String = ""
        var minImagesCntMsg: String = ""//用于image类型的配置了最小image数量的校验
        let allRequiredCheckList: [PVDChecklistModel] = JobDetailModelHelper.shared.jobDetailModel.pvd_checklists.filter({$0.is_required == "true" && ($0.type == ChecklistType.Image.rawValue || $0.type == ChecklistType.Text.rawValue || $0.type == ChecklistType.Bool.rawValue)})
        
        for checklistModel in allRequiredCheckList {
            let title = checklistModel.title
            switch checklistModel.type {
                case ChecklistType.Bool.rawValue:
                    if checklistModel.answer == "" || checklistModel.answer == "false" {
                        alertMsg += "* " + title + " must be checked.\n"
                    }
                case ChecklistType.Image.rawValue:
                    //ESC单独处理,如果COC附件有数据，则表示此checklist已完成（也不用检查是否满足最小数量）
                    let cocCnt = JobDetailModelHelper.shared.jobDetailModel.coc_documents.count
                    let electricalFlag = checklistModel.actions.electrical
                    if electricalFlag && cocCnt > 0{
                        
                    }else{//其他情况
                        let realImageCount = checklistModel.images.count
                        if realImageCount == 0 {
                            alertMsg += "* " + title + " must be checked.\n"
                        }else {
                            let minImagesCnt = checklistModel.minimum_quantity
                            if realImageCount < minImagesCnt{//如果checklist的image 数量小于配置的最小图片数量，也要提示没有完成
                                minImagesCntMsg += " - " + title + " (\(realImageCount)/\(minImagesCnt)).\n"
                            }
                        }
                    }
                case ChecklistType.Text.rawValue:
                    if checklistModel.answer == "" {
                        alertMsg += "* " + title + " must be checked.\n"
                    }
                default:
                    break
            }
        }
        return (alertMsg, minImagesCntMsg)
    }
    //MARK: - 校验PVD必填项：true: checked, false: verified
    func checkRequiredWhenFinishJob()->Bool{
        var alertMsg: String = ""
        //NMI校验
        if JobDetailModelHelper.shared.jobDetailModel.system_detail.connected_type == GridConnectedValue.onGrid.rawValue && JobDetailModelHelper.shared.jobDetailModel.install_address.isNMIRequired{
            if JobDetailModelHelper.shared.jobDetailModel.install_address.nmi == "" {
                alertMsg += "* NMI in Grid-Connected is required.\n"
            }
        }
        //check if panel installed when spv check is true
        if JobDetailModelHelper.shared.jobDetailModel.spv_check && !JobDetailModelHelper.shared.jobDetailModel.spv_installed {
            alertMsg += "* Date of Commissioning in certificates must be checked.\n"
        }
        //******1.Checklist
        let (checklistMsg, minImagesCntMsg) = self.checkIfChecklistAllDoneForFinishJob()
        if checklistMsg != ""{
            alertMsg += checklistMsg
        }
        //******2.Signatures
        //installer
        if JobDetailModelHelper.shared.jobDetailModel.signatures.installer_signed_signature == ""{
            alertMsg += "* Installer signature must be signed.\n"
        }
        //designer
        if JobDetailModelHelper.shared.jobDetailModel.signatures.designer_signed_signature == ""{
            alertMsg += "* Designer signature must be signed.\n"
        }
        //witness
        if JobDetailModelHelper.shared.jobDetailModel.is_new_stc_form == false{//4月1号之前的Job，才验证witness
            if JobDetailModelHelper.shared.jobDetailModel.signatures.witness_signed_signature == "" {
                alertMsg += "* Witness signature must be signed.\n"
            }
        }
        
        //******3.panel numbers
        if JobDetailModelHelper.shared.jobDetailModel.pvd_serial_numbers.count == 0 {
            alertMsg += "* Panel serial numbers can't be empty.\n"
        }
        //组合最小image 数量校验的信息
        if minImagesCntMsg != ""{
            alertMsg += "\n* Additional checklist photos required for the following sections:\n" + minImagesCntMsg
        }
        //*****2022-04-01后创建的Job才校验inverter
        if JobDetailModelHelper.shared.jobDetailModel.is_new_stc_form{
            let systemDetail = JobDetailModelHelper.shared.jobDetailModel.system_detail
            //计划数量大于0才做校验
            let planInverterNumberCnt = systemDetail.inverter_plant_count
            let scannedInverterNumberCnt = JobDetailModelHelper.shared.jobDetailModel.pvd_inverter_serial_numbers.count //已经扫描的数据
            if planInverterNumberCnt != scannedInverterNumberCnt {//计划数量和扫描数量不一样
                alertMsg += "* The actual number of inverters installed do not match with the original quantity.\n Inverter quantity: \(planInverterNumberCnt)" +  "\n Inverter serial numbers: \(scannedInverterNumberCnt)"
            }else{//计划数量和扫描数量一样，检查是否都有图片
                for inverterModel in JobDetailModelHelper.shared.jobDetailModel.pvd_inverter_serial_numbers{
                    if inverterModel.image == "" {
                        alertMsg += "* Missing inverter serial number photo(s)."
                        break
                    }
                }
            }
        }
        
        if alertMsg.count > 0 {
            Tool().showAlertViewWithOneBtn(title: "Job can not be finished due to following tasks",message: alertMsg,messageTextAlignment: .left)
            return false
        }
        return true
    }
    //MARK: - 校验SWH必填项：true: checked, false: verified
    func checkRequiredWhenFinishJobForSWH()->Bool{
        var alertMsg: String = ""
        
        //******1.Checklist
        let (checklistMsg, minImagesCntMsg) = self.checkIfChecklistAllDoneForFinishJob()
        if checklistMsg != ""{
            alertMsg += checklistMsg
        }
        //******2.Signatures
        //installer（从4.1.2 installer改成非必填）
//        if JobDetailModelHelper.shared.jobDetailModel.signatures.installer_signed_signature == ""{
//            alertMsg += "* Installer signature must be signed.\n"
//        }
        //******3.tank numbers（校验必填项）
        if JobDetailModelHelper.shared.jobDetailModel.pvd_inverter_serial_numbers.count == 0 {//热水器时
            alertMsg += "* Tank serial numbers can't be empty.\n"
        }
        //组合最小image 数量校验的信息
        if minImagesCntMsg != ""{
            alertMsg += "\n* Additional checklist photos required for the following sections:\n" + minImagesCntMsg
        }
        if alertMsg.count > 0 {
            Tool().showAlertViewWithOneBtn(title: "Job can not be finished due to following tasks",message: alertMsg,messageTextAlignment: .left)
            return false
        }
        return true
    }
    //only for cache request data
    func cacheJobDetail(_ loadingText:String = "", successClosure:(()->Void)? = nil, faildClosure:((String,String)->Void)? = nil)
    {
        let vm = JobDetailService()
        //set block
        vm.setBlockAfterNetwork({ (result , _) -> Void in
            if loadingText != ""{
                ModelViewUtil.shared.hideLoadingView()
            }
            successClosure?()
            
        }) { (code, error) -> Void in
            if loadingText != ""{
                ModelViewUtil.shared.hideLoadingView()
            }
            faildClosure?(code,error)
        }
        if loadingText != ""{
            ModelViewUtil.shared.showLoadingView(loadingText)
        }
        vm.getInstallationsDetail(cacheFlag: false)
    }
    
    //检查需要顺序操作的checklist的相关提示
    func checkOrderChecklist(model: PVDDetailModel,checklistModel: PVDChecklistModel, closure : @escaping ()->Void){
        let currentChecklistModel = checklistModel
        let checklistID = currentChecklistModel.id
        var nextDoneFlag = false
        switch checklistID {
            case ChecklistFixedId.preInstall.rawValue:
                if let midInstall = model.pvd_checklists.first(where: {$0.id == ChecklistFixedId.midInstall.rawValue}), midInstall.images.count > 0{
                    nextDoneFlag = true
                }
                if nextDoneFlag {//mid已完成
                    let title = currentChecklistModel.title.replacingOccurrences(of: "Selfie", with: "")
                    Tool().showAlertViewWithTwoBtns(title: R.string.localizable.reminder(), message: R.string.localizable.pleaseTakeSelfiesInTheCorrectTimeOrderFromStartToFinishConfirmToRetakeAllSelfiesFrom(title), cancelStr: R.string.localizable.goBack(), confirmStr: R.string.localizable.confirm(), yesClosure:  {
                        closure()//确认继续拍照
                    })
                }else{
                    closure()//去拍照
                }
            case ChecklistFixedId.midInstall.rawValue:
                if let midInstall = model.pvd_checklists.first(where: {$0.id == ChecklistFixedId.testAndCommission.rawValue}), midInstall.images.count > 0{
                    nextDoneFlag = true
                }
                if nextDoneFlag {//Test and commission已完成
                    let title = currentChecklistModel.title.replacingOccurrences(of: "Selfie", with: "")
                    Tool().showAlertViewWithTwoBtns(title: R.string.localizable.reminder(), message: R.string.localizable.pleaseTakeSelfiesInTheCorrectTimeOrderFromStartToFinishConfirmToRetakeAllSelfiesFrom(title), cancelStr: R.string.localizable.goBack(), confirmStr: R.string.localizable.confirm(), yesClosure:  {
                        //检查时间间隔是否符合
                        let settingMins = currentChecklistModel.photo_interval
                        if settingMins > 0 {
                            let overFlag = self.checkIfChecklistIsOverInterval(ChecklistFixedId.preInstall.rawValue, settingInternal: settingMins)
                            if overFlag {//已经过了时间间隔,可以操作
                                closure()//去拍照
                            }else{//还没有超过设定的时间间隔，给与提示
                                Tool().showAlertViewWithTwoBtns(title: R.string.localizable.reminder(), message: R.string.localizable.pleaseTakeSelfiesWithAReasonableTimeIntervalOfAtLeastMinsBetweenEachStage("\(settingMins)"), cancelStr: R.string.localizable.goBack(), confirmStr: R.string.localizable.continue(),yesClosure: { closure()})
                            }
                        }else{
                            closure()//去拍照
                        }
                    })
                }else{//检查时间间隔是否符合
                    let settingMins = currentChecklistModel.photo_interval
                    if settingMins > 0 {
                        let overFlag = self.checkIfChecklistIsOverInterval(ChecklistFixedId.preInstall.rawValue, settingInternal: settingMins)
                        if overFlag {//已经过了时间间隔,可以操作
                            closure()//去拍照
                        }else{//还没有超过设定的时间间隔，给与提示
                            Tool().showAlertViewWithTwoBtns(title: R.string.localizable.reminder(), message: R.string.localizable.pleaseTakeSelfiesWithAReasonableTimeIntervalOfAtLeastMinsBetweenEachStage("\(settingMins)"), cancelStr: R.string.localizable.goBack(), confirmStr: R.string.localizable.continue(),yesClosure: { closure() })
                        }
                    }else{
                        closure()//去拍照
                    }
                    
                    
                }
            case ChecklistFixedId.testAndCommission.rawValue:
                let settingMins = currentChecklistModel.photo_interval
                if settingMins > 0 {
                    let overFlag = self.checkIfChecklistIsOverInterval(ChecklistFixedId.midInstall.rawValue, settingInternal: settingMins)
                    if overFlag {//已经过了时间间隔,可以操作
                        closure()//去拍照
                    }else{//还没有超过设定的时间间隔，给与提示
                        Tool().showAlertViewWithTwoBtns(title: R.string.localizable.reminder(), message: R.string.localizable.pleaseTakeSelfiesWithAReasonableTimeIntervalOfAtLeastMinsBetweenEachStage("\(settingMins)"), cancelStr: R.string.localizable.goBack(), confirmStr: R.string.localizable.continue(),yesClosure: { closure() })
                    }
                }else{
                    closure()//去拍照
                }
                
        default:
            break
        }
        
    }
    //获取某个checklist中最新的photo时间
    fileprivate func getLatestPhotoDate(_ checklistID: Int32)->String{
        var latestDate: String = ""
        var combineList = [CheckListImageDBModel]()
        //server image list
        if let checklistModel = JobDetailModelHelper.shared.jobDetailModel.pvd_checklists.first(where: {$0.id == checklistID}){
            combineList = checklistModel.images
        }
        //local image list
        if let checklistModel = JobDetailModelHelper.shared.jobDetailModel.localChecklists.first(where: {$0.id == checklistID}){
            combineList += checklistModel.localAddImages
        }
        //降序排列
        let imagesList = combineList.sorted { m1, m2 in
            //date one
            var dateOneStr: String = ""
            if m1.photo_created_at != ""   {
                dateOneStr = m1.photo_created_at
            }else if  m1.record_at != ""{
                dateOneStr = m1.record_at
            }
            //date two
            var dateTwoStr: String = ""
            if m2.photo_created_at != ""  {
                dateTwoStr = m2.photo_created_at
            }else if  m2.record_at != ""{
                dateTwoStr =  m2.record_at
            }
            
            if let dateOne = DateUtil().convertDateTimeStrToDate(dateOneStr),let dateTwo = DateUtil().convertDateTimeStrToDate(dateTwoStr){
                let datetimeInternel = dateOne.timeIntervalSince(dateTwo)
                if datetimeInternel > 0 {
                    return true
                }
            }
            return false
        }
        //获取第一个，最近日期的
        if imagesList.count > 0 {
            if imagesList[0].photo_created_at != ""  {
                latestDate = imagesList[0].photo_created_at
            }else if imagesList[0].record_at != ""  {
                latestDate = imagesList[0].record_at
            }
        }
        return latestDate
    }
    //检查上一个checklist的最新图片时间到现在是否超过设置的间隔时间
    fileprivate func checkIfChecklistIsOverInterval(_ checklistID: Int32, settingInternal: Int) -> Bool{
        //默认已经超过设定的时间间隔的
        var resultFlag: Bool = true
        //最新的date
        let latestDateStr = self.getLatestPhotoDate(checklistID)
        if let latestDate = DateUtil().convertDateTimeStrToDate(latestDateStr){
            let nowDate = Date()
            let realInternalSecond = Int(nowDate.timeIntervalSince(latestDate))
            if realInternalSecond < settingInternal * 60 {//超过间隔时间
                resultFlag = false
            }
        }
        return resultFlag
    }
    func callPhone(_ phoneNumber: String){
        let callPhone = APPConfig.CallPhoneURL + phoneNumber
        if let url = URL(string: callPhone){
            if UIApplication.shared.canOpenURL(url){
                UIApplication.shared.open(url, options: [:], completionHandler: nil)
            }
        }
    }
    func sendEmail(_ email: String?){
        guard let mailBox = email else {return}
        let urlStri: String = APPConfig.SendEmailURL + mailBox
        if let url = URL(string: urlStri), UIApplication.shared.canOpenURL(url){
            UIApplication.shared.open(url, options: [:], completionHandler: nil)
        }
    }
    func copyContentToPasteBoard(content: String,parentView: UIView){
        UIPasteboard.general.string = content // pasteboardStr就是你要复制的字符串JobDetailModelHelper.shared.jobDetailModel.install_address.installation_address
        MBProgressHUD.showToast(parentView: parentView, text: "Copy address succesfully")
    }
    //MARK: - 从三个主界面跳转到Me界面
    func toMeViewController(_ parentVC: BaseViewController){
        let vc = MeViewController()
        vc.hidesBottomBarWhenPushed = true
        parentVC.navigationController?.pushViewController(vc, animated: false)
    }
    //MARK: 获取job的本地数量，用户job detail中的flush upload的数量显示，及是否有本地数据
    func getCountOfLocalData(_ model: PVDDetailModel)->Int{
        var totalCnt: Int = 0
        //1.panel新增和修改的数量
        let panelAddAndModifyList = model.pvd_serial_numbers.filter({$0.operType == DataOperType.Add.rawValue || $0.operType == DataOperType.Modify.rawValue})
        
        //2.inverter新增和修改的数量
        let inverterAddAndModifyList = model.pvd_inverter_serial_numbers.filter({$0.operType == DataOperType.Add.rawValue || $0.operType == DataOperType.Modify.rawValue})
        //3.checklist中bool或text
        let checklistBoolAndTextList = model.pvd_checklists.filter({$0.oper_type == DataOperType.Add.rawValue})
        //4.checklist中image
        var checklistImagesCnt: Int = 0
        _ =  model.pvd_checklists.filter({$0.type == ChecklistType.Image.rawValue}).map { checklistModel in
            let addList = checklistModel.images.filter({$0.oper_type == DataOperType.Add.rawValue})
            checklistImagesCnt += addList.count + checklistModel.localDeletedImages.count
        }
        //5.panel ,inverter, image的删除数据
        
        //6.signature 本地数量
        let localSignatures = model.localSignatures
        totalCnt = (localSignatures.installer == nil ? 0 : 1) + (localSignatures.designer == nil ? 0 : 1) + (localSignatures.owner == nil ? 0 : 1) + (localSignatures.witness == nil ? 0 : 1)
        //
        totalCnt += panelAddAndModifyList.count + model.localDeletedSerialNumbers.count + inverterAddAndModifyList.count + model.localDeletedInverterNumbers.count + checklistBoolAndTextList.count + checklistImagesCnt
        return totalCnt
    }
    //MARK: - 只用于刷新数据
    func cacheData(closure: ((Bool)->Void)? = nil)
    {
        //set block
        let viewModel = JobDetailService()
        viewModel.setBlockAfterNetwork({ (result , _) -> Void in
            closure?(true)
        }) { (code, error) -> Void in
            closure?(false)
        }
            
        viewModel.getInstallationsDetail()
    }
    //MARK: - 检查panels是否是有一个band的数据（包括一个或多个model）
    func checkIfHaveOnlyOneBandForSPV(_ panels: [InstallationDetailSystemDetailForPanelModel])->Bool{
        var haveOneBrand = false
        if panels.count > 0 {
            let firstBrand = panels[0].brand
            let otherBrand = panels.filter({$0.brand != firstBrand})
            if otherBrand.count == 0 {
                haveOneBrand = true
            }
        }
        return haveOneBrand
        
    }
    //MARK: - 下个动作（包括create，edit panel，edit system info）前先校验是否弹出spv check的提示
    func validSPVCheckBeforeNextOperation(panels: [InstallationDetailSystemDetailForPanelModel], companyID: Int,_ closure: ((Bool)->Void)?){
        let service = CreateJobService()
        service.setBlockAfterNetwork { result, otherInfo in
            ModelViewUtil.shared.hideLoadingView()
            if let dic = result as? NSDictionary, let spvCheck = dic.object(forKey: "spv_check") as? Bool, spvCheck {
                closure?(true)
            }else{
                closure?(false)
            }
            
        } errorBlock: { code, error in
            ModelViewUtil.shared.hideLoadingView()
            Tool().showErrorInfo(code,error)
        }
        ModelViewUtil.shared.showLoadingView("Valid SPV Check...")
        service.validSPVCheckBeforeUpdatePanel(panels: panels, companyID: companyID)
    }
    //MARK: - 获取Job Detail VC
    func getJobDetaiVC(_ vc: UINavigationController?)->BaseViewController?{
        var jobDetailVC: BaseViewController?
        guard let naviVC = vc else{
            return nil
        }
        for vc in naviVC.viewControllers{
            if let tempVC = vc as? JobDetailViewController{
                jobDetailVC = tempVC
            }else if let tempVC = vc as? SWHDetailViewController{
                jobDetailVC = tempVC
            }
        }
        return jobDetailVC
    }
}
